package com.yst.shader.feature.widget

import android.content.Context
import android.graphics.*
import android.graphics.Canvas.ALL_SAVE_FLAG
import android.graphics.drawable.Drawable
import android.graphics.drawable.NinePatchDrawable
import android.util.AttributeSet
import android.view.View
import androidx.appcompat.widget.AppCompatImageView
import androidx.core.graphics.withSave
import com.yst.shader.R
import com.yst.shader.feature.shimmer.ShimmerView
import kotlin.random.Random

/**
 * @author: xuyujian@ysten.com
 *  @date: 2020/8/18 22:06
 */
class CanvasShimmerView : ShimmerView {

    constructor(context: Context) : super(context)
    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs)

    private val source by lazy { BitmapFactory.decodeResource(resources, R.drawable.test) }
    private val focus by lazy { BitmapFactory.decodeResource(resources, R.drawable.focus_red) }
    private val focusDrawable by lazy { resources.getDrawable(R.drawable.share_vip_focus) }
    private val focusCircleDrawable by lazy { resources.getDrawable(R.drawable.share_item_circle_bg_focus_v2_vip) }
    private val lowFocus by lazy { resources.getDrawable(R.drawable.share_bg_focus_home_v2_low_device) }
    private val paint by lazy { Paint() }
    private val temp = Rect()
    private val outerRect = 100f

    init {
        shimmer()
        var padding = focusDrawable.getPadding(temp)
        println("focus  padding $ ,value $temp")
        padding = focusCircleDrawable.getPadding(temp)
        println("focus  padding $ ,value $temp")
        this.enableShimmer = true
        focusSelectDrawable = lowFocus
        setLayerType(1, paint)
    }

    lateinit var focusSelectDrawable: Drawable
    override fun onFocusChanged(gainFocus: Boolean, direction: Int, previouslyFocusedRect: Rect?) {
        super.onFocusChanged(gainFocus, direction, previouslyFocusedRect)
        if (gainFocus) {
            // startShimmer()

            focusSelectDrawable.getPadding(temp)
            startShimmer()
        } else {
            over = false
        }
    }

    val r = Random(System.currentTimeMillis())
    var over = false
    var onFocused = false

    override fun onDraw(canvas: Canvas) {
        println("onDraw ${hashCode()}")
        super.onDraw(canvas)
        if (onFocused || isFocused) {
            if (focusSelectDrawable !is NinePatchDrawable) {
                focusSelectDrawable.bounds = Rect(-100, -100, width + 100, height + 100)
                focusSelectDrawable.draw(canvas)
            } else {

                focusSelectDrawable.bounds =
                    Rect(-temp.left, -temp.top, width + temp.right, height + temp.bottom)
                focusSelectDrawable.draw(canvas)
            }
        }
    }
}